import 'package:casdon/core/logger/log.dart';
import 'package:casdon/modules/login/domain/validators/email_validator.dart';
import 'package:casdon/modules/login/domain/validators/phone_validator.dart';

abstract class InputValidator {
  bool isValude(String input);
  String? validateWithMessage(String input);
}

enum CombinedType { and, or }

class CombinedValidator implements InputValidator {
  final List<InputValidator> validators;
  final CombinedType type;

  /// 主构造函数
  const CombinedValidator(this.validators, {this.type = CombinedType.or});

  /// 便捷构造函数
  factory CombinedValidator.withDefaults() {
    return CombinedValidator([EmailValidator(), PhoneValidator()]);
  }

  /// 实现抽象方法
  @override
  bool isValude(String input) {
    bool value = true;
    for (final validator in validators) {
      final ret = validator.isValude(input);
      if (type == CombinedType.and) {
        value = false;
      }
      if (ret == value) return ret;
    }
    return !value;
  }

  @override
  String? validateWithMessage(String input) {
    List<bool> resultList = [];
    bool ret = false;
    for (final validator in validators) {
      final error = validator.validateWithMessage(input);
      resultList.add(error == null);
    }
    if (type == CombinedType.and) {
      ret = resultList.every((element) => element == true);
    } else {
      ret = resultList.any((element) => element == true);
    }
    return ret ? null : "账号不合法";
  }
}
